
<style lang="scss">
  .el-dialog.is-fullscreen{
    .el-dialog__body {
      height: calc(100% - 120px);
    }
  }

 
</style>
<template>
  <basic-container>
    <!-- 表格 -->
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :defaults.sync="showColumn"
               :permission="permissionList"
               :page.sync="reqParams"
               :before-open="beforeOpen"
               @sortable-change="sortableChange"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @filter="filterChange"
               @sort-change="sortChange"
               @row-dblclick="handleRowDBLClick"               
               @on-load="onLoad">
      <template slot-scope="scope" slot="menuForm">
        <div  style="text-align:right; float:right">
          <el-button type="text"  v-if="operateType == 'edit'"   icon="el-icon-time" style="font-weight:normal;" size="large" @click.stop="getHistoryRecord">修改历史</el-button>
        </div> 
      </template>
      <template slot-scope="scope" slot="menuLeft">
        <!-- 批量新增 -->
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.general_staff_station_batch_add" @click.stop="openBatchAddDialog">批量新增</el-button>
        <!-- 删除 -->
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.general_staff_station_batch_delete" @click.stop="handleDelete">删 除</el-button>
        <!-- 上传 -->
        <el-button type="primary" size="small" icon="el-icon-delete" @click.stop="file.dialog = true">上 传</el-button>
      </template>
      <template slot="menuRight">
        <!-- 下载 -->
        <el-button v-if="permission.general_staff_station_download" type="default" @click.stop="exportExcel"  title="下载" icon="el-icon-download" circle size="small"></el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text" icon="el-icon-edit" @click="entryData.dialog = true">编辑</el-button>
      </template>
    </avue-crud>

    <!-- 批量添加数据对话框 -->
    <el-dialog title="批量导入" width='80%' :close-on-click-modal='false' :visible.sync="importData.dialog">
      <!-- 标题 -->
      <el-tag>ID,租户ID,办公区编号,楼层编号,工位编号,工位性质,工位类型,工位状态,所属项目名称,所属部门名称,使用人名,管理员用户名,工位使用率,出勤状态,联系电话</el-tag>
      <!-- 内容 -->
      <el-input  type="textarea"  :autosize="{ minRows: 10, maxRows: 20}" placeholder="请直接从excel粘贴内容"  v-model="importData.data"></el-input>
      <div slot="footer" class="dialog-footer">
        <!-- 按钮 --> 
        <el-button size="small" type="primary" id="copyBtn" @click="handleImport($event)" data-clipboard-target="#pathText">开始导入</el-button>
        <el-button size="small" @click="importData.dialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 历史记录 -->
    <update-history ref="historyRecord"></update-history>

     <!-- 批量添加数据对话框 -->
    <el-dialog title="设置条目" custom-class='entry-diolog' :fullscreen="true" :close-on-click-modal='false' :visible.sync="entryData.dialog" :destroy-on-close="true">
      <!-- 批量设置条目 -->
      <set-entry :url="file.url"></set-entry>
      <div slot="footer">
        <!-- 按钮 --> 
        <el-button size="small" type="primary" @click="entryData.dialog=false">保 存</el-button>
        <el-button size="small" @click="entryData.dialog=false">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 上传文件对话框-->
    <el-dialog title="上传文件" width='800px' :close-on-click-modal='false' :visible.sync="file.dialog" @close="closeFileDialog()">
      <el-upload class="fileUpload"
        action="/file/upload"
        :headers="file.headersParam"
        multiple
        :limit="10"
        drag
        :on-success="handleSuccess"
        :file-list="file.fileList">
       <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传word文件,且不超过500kb</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn"  v-if="file.saveBtn" @click="handlelSaveFile($event)" data-clipboard-target="#pathText">解 析</el-button>
      </div>
    </el-dialog>

  </basic-container>
</template>

<script>
import {exportGeneralStaffStationExcel,saveOrUpdateGeneralStaffStation,saveOrUpdateGeneralStaffStationList,saveGeneralStaffStation,saveGeneralStaffStationList,deleteGeneralStaffStation,queryGeneralStaffStation,queryGeneralStaffStationListPage,updateGeneralStaffStation,deleteGeneralStaffStationList} from '@/api/general/station/generalStaffStationApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
import setEntry from './setEntry.vue'
import {getToken} from '@/util/auth'
export default {
  data() {
    return {
      // 当前打开form对话框操作类型 
      operateType: 'add', 
      // 批量导入
      importData:{
        data:'',
        dialog:false
      },
      // 编辑表单值
      form: {},
      // 复选框
      selectionList: [],
      // 列表加载
      loading: false, 
      // 列表显示字段
      showColumn: [],
      // 列表显示的数据
      data: [],
      // 列表参数
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: [],
        currentPage: 1,
        pageSize: 10,
        total:0
      },
      // 配置项
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 125,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: true,
        align:'center',
        viewBtn: false,
        delBtn: true,
        cancelBtn: true,
        editBtn:false,
        printBtn:false,
        saveBtn: true,
        filterBtn:true,          
        menuWidth: 200,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        column: [
          // 办公区编号
          {
            label: '需求编号',
            prop: 't1', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 30,
            overHidden: true,
            rules: [{
              message: '请输入需求编号',
              required:  true,
              trigger: 'blur'
            },
            {
              max: 30,
              message: '内容长度不能超过30字符',
              trigger: 'blur'
            }],
            didicData:[],
          },
        ]
      },
      // 设置条目数据
      entryData:{
        dialog:false,
      },
      // 文件
      file:{
        dialog:false,
        saveBtn:false,
        headersParam:{},
        fileList:[],
        url:'',
      }
    };
  },
  components: {
    setEntry
  },
  computed: {
    ...mapGetters(['website','orgTree','genOrgTree','userInfo','permission','projectInfo']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.general_staff_station_add, false),
        viewBtn: this.vaildData(this.permission.general_staff_station_view, false),
        delBtn: this.vaildData(this.permission.general_staff_station_delete, false),
        editBtn: this.vaildData(this.permission.general_staff_station_edit, false),
        printBtn: this.vaildData(this.permission.general_staff_station_print, false),
        searchBtn:this.vaildData(this.permission.general_staff_station_search, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: {
    /**
     * 加载列表数据
     */
    onLoad(params) {
      this.loading = true;
      queryGeneralStaffStationListPage(reqCommonMsg(params)).then(res => {
        const data = res.data.body;
        this.data = data.listBody;
        // 模拟数据
        this.data = [{t1:'RNG001'},{t1:'RNG002'},{t1:'RNG003'}];
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      if(this.permission.general_staff_station_dbclick){
        this.$refs.crud.rowView(row,row.$index);
      }
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.reqParams = {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: [],
        currentPage: 1,
        pageSize: 10,
        total:0
      };
      this.onLoad(this.reqParams);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.reqParams.singleBody = params
      this.reqParams.currentPage = 1;
      this.onLoad(this.reqParams);
      done();
    },
    /**
     * 重置刷新
     */
    refreshChange(){
      this.onLoad(this.reqParams);
    },
    /**
     * 复选框事件
     */
    selectionChange(list) {
      this.selectionList = list;
    },
    /**
     * 清除复选框
     */
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.reqParams.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.reqParams.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.reqParams.currentPage = 1;
      this.reqParams.sqlCondition = filterFormat(result)
      this.onLoad(this.reqParams);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.reqParams.orderRule = val;
      this.onLoad(this.reqParams);
    },
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams.currentPage = 1;
      this.reqParams.pageSize = 100;
      exportGeneralStaffStationExcel(reqCommonMsg(this.reqParams));
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return deleteGeneralStaffStationList(reqCommonMsg({listBody:this.ids}));
        })
        .then(() => {
          this.onLoad(this.reqParams);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      this.importData.dialog = true;
    },
    /**
     * 调用子组件方法查询历史
     */
    getHistoryRecord () {
      setTimeout(() => {
        this.$refs.historyRecord.getUpdateHistoryRecord(this.form.id);
      })
    },
    /**
     * ===============================================
     * 自定义
     */
    /**
     * 编辑
     */  
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        this.operateType = 'edit';
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading'
        });
        queryGeneralStaffStation(reqCommonMsg( {singleBody: {id:this.form.id}})).then(res => {
          let form = res.data.body.singleBody;
          // 使用人名,管理员用户名显示拼接
          form.useRealName = form.useRealName + (form.useUserName?'('+ form.useUserName +')':'');
          form.managerUserName = form.managerRealName + (form.managerUserName?'('+ form.managerUserName +')':'');
          this.form = form;
          loading.close();
          done();
        }, error => {
          loading.close();
          done();
        });
      }
      if (['add'].includes(type)) {
        this.operateType = 'add';
        done();
      }
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      let params ={
        singleBody:{
          ...row,
          useRealName:this.$util.formatUserName(row.useRealName).userName,// 使用人名
          useUserName:this.$util.formatUserName(row.useRealName).userId,// 使用用户名
          managerUserName:this.$util.formatUserName(row.managerUserName).userName,// 管理员用户名
          managerRealName:this.$util.formatUserName(row.managerUserName).userId,// 管理员人名
        },
        currentPage: 0,
        pageSize: 0
      };
      saveGeneralStaffStation(reqCommonMsg(params)).then(() => {
        done();
        this.onLoad(this.reqParams);
        this.$message({type: 'success', message: '操作成功!'});
      }, error => {
        done();
      });
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) {
      let params ={
        singleBody:{
          ...row,
          useRealName:this.$util.formatUserName(row.useRealName).userName,// 使用人名
          useUserName:this.$util.formatUserName(row.useRealName).userId,// 使用用户名
          managerUserName:this.$util.formatUserName(row.managerUserName).userName,// 管理员用户名
          managerRealName:this.$util.formatUserName(row.managerUserName).userId,// 管理员人名
        },
        currentPage: 0,
        pageSize: 0
      };
      updateGeneralStaffStation(reqCommonMsg(params)).then(() => {
        done();
        this.onLoad(this.reqParams);
        this.$message({type: 'success',message: '操作成功!'});
      }, error => {
        done();
      });
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'})
        .then(() => {
          return deleteGeneralStaffStation(reqCommonMsg({singleBody:row}));
        })
        .then(() => {
          this.onLoad(this.reqParams);
          this.$message({type: 'success',message: '操作成功!'});
        }).catch(() => {});
    },
    /**
     * 批量导入
     */
    handleImport() {
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading',
      });
      var dataList = new Array();
      if(this.importData.data){
        var lineList = this.importData.data.split('\n')
        lineList.forEach((element,index) => {
          if(element.trim() != ''){
            var field = element.split('\t')
            let fieldList = {
              id:field[0].trim(),
              tenantId:field[1].trim(),
            };
            this.option.column.forEach((item,index)=>{
              fieldList1[item.prop] = field[index + 2].trim();
            });
            dataList[index] = fieldList
          }
        });
        //批量写入记录
        saveGeneralStaffStationList(reqCommonMsg({listBody:dataList})).then(() => {
          this.onLoad(this.reqParams);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          loading.close();
        }, error => {
          loading.close();
        });      
      }
      else{
        this.loading=false;
        this.$message({
          type: 'warning',
          message: '数据格式不正确!'
        });
      }
    },
    /**
     * 上传成功回调
     */
    handleSuccess(response, file, fileList){
      if(response.head.respCode == 'S0000'){
        this.file.fileList = fileList;
        this.file.saveBtn = true;
      }
      else{
        file.status = 'error';
        this.$message({customClass:'zZindex',type: 'error',message: response.head.respMsg});
        this.file.saveBtn = false;
      }
    },
    /**
     * 保存记录
     */
    handlelSaveFile() {
      // const loading = this.$loading({
      //   lock: true,
      //   text: 'Loading',
      //   spinner: 'el-icon-loading',
      // });
      // 关联文档url与数据
      // var dataList = [];
      // if(this.file.fileList.length > 0){
      //   this.file.fileList.forEach((element,index) => {
      //     if(element.status  ==  'success'){
      //       dataList.push({
      //         fileName: element.response.fileName,
      //         filePath:element.response.filePath,
      //         fileSize:element.response.fileSize,
      //         fileType:element.response.fileType,
      //         catalogId: this.currentCatalog.id,
      //         ownerId: this.userInfo.userId
      //       });
      //     }
      //   });
      //   //批量写入记录
      //   saveGeneralFileInfoList(reqCommonMsg({listBody:dataList,currentPage:1,pageSize:10})).then(() => {
      //     this.onLoad(this.reqParams);
      //     this.$message({customClass:'zZindex',type: 'success',message: '操作成功!'});
      //     loading.close();
      //     this.file.dialog = false;
      //   }, error => {
      //     //this.$console.log(error);
      //     loading.close();
      //     this.file.dialog = false;
      //   });      
      // }
      // else{
      //   this.$message({customClass:'zZindex',type: 'error',message: '请选择文件上传后再保存!'});
      //   loading.close();
      // }

      this.file.dialog = false;
      this.file.url = this.file.fileList[0].response.filePath;

      this.entryData.dialog = true;
      // 解析
      // analysisWord(reqCommonMsg({listBody:dataList,currentPage:1,pageSize:10})).then(() => {
        
      //   this.$message({customClass:'zZindex',type: 'success',message: '解析成功!'});
      //   loading.close();
      //   this.file.dialog = false;
      //   this.file.url = this.file.fileList[0].response.filePath;
      //   this.entryData.dialog = true;
      // }, error => {
      //   //this.$console.log(error);
      //   loading.close();
      //   this.file.dialog = false;
      // });      

    },
    // 关闭上传文件弹框
    closeFileDialog(){
      this.file.dialog = false;
      this.file.saveBtn = false;
      this.file.fileList = [];
    },
  },
  mounted() {
    // this.showColumn = this.$getStore({name: this.userInfo.userId+'generalStaffStationColumn'});
    this.showColumn = ['t1'];
    this.file.headersParam={
      'Authorization': 'bearer ' + getToken(),
      'UserId': this.userInfo.userId,
      'UserSign':'uploadFile',
      'remote': 'no'
    };
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'generalStaffStationColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name:  this.userInfo.userId+'generalStaffStationColumn', content: this.showColumn});
    }
  }
};
</script>
